package kr.co.bettersoft.usedmarketandroid.activity;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import kr.co.bettersoft.usedmarketandroid.common.CommonConstant;
import kr.co.bettersoft.usedmarketandroid.common.CommonUtil;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

/**
 * ImageViewer
 * 채팅방에서 업로드한 이미지를 크게 볼수 잇고
 *  다운로드 기능을 제공하는 액티비티이다.
 * @author blue
 *
 */
public class ImageViewer extends Activity {
	///////////////////////////////////////////////////////////////////////////////////////////////
	// 변수

	public String TAG = "ImageViewer";

	String imageUrl;				// 업로드 이미지 URL
	Bitmap temp_upload_img;			// 업로드 이미지

	ImageView upload_img_view;		// 업로드 이미지 크게보기 뷰
	ProgressBar pb1;			// 중단 로딩 진행바

	Button top_navi_close_btn;
	Button image_download_btn;


	CommonUtil commonUtil;

	///////////////////////////////////////////////////////////////////////////////////////////////////

	// 핸들러
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			try{
				Bundle b = msg.getData();		
				//				// 상단 타이틀 문구 변경
				//				if(b.getInt("titleChange")==1){
				//					chatRoomTitle.setText(recievedOwner+" 님의 채팅방");
				//				}

				// 업로드 이미지 상세 보기
				if(b.getInt("showUploadImage")==1){
					upload_img_view.setImageBitmap(temp_upload_img);
					hidePb();
					//			  		upload_img_view.setVisibility(View.VISIBLE);
				}

				// 화면에 토스트
				if(b.getInt("showToast")==1){		// 화면에 토스트 띄우기. 띄우는 문구는 msg 로 받은 값
					Toast.makeText(ImageViewer.this, b.getString("msg"), Toast.LENGTH_SHORT).show();
				}
				// 화면에 알림창
				if(b.getInt("showAlert")==1){					 // 경고창 . 
					new AlertDialog.Builder(returnThis())
					.setTitle(CommonConstant.alertTitle)							 
					.setMessage(b.getString("msg"))
					.setIcon(R.drawable.ic_launcher)		
					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							//
						}})
						.setNegativeButton("", null).show();
				}
				if(b.getInt("order")==1){
					// 프로그래스바 실행
					pb1.setVisibility(View.VISIBLE);
				}else if(b.getInt("order")==2){
					// 프로그래스바  종료
					pb1.setVisibility(View.INVISIBLE);
				}

			}catch(Exception e){
				e.printStackTrace();
			}
		}
	};

	///////////////////////////////////////////////////////////////////////////////////////////////////

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.w(TAG, "ImageViewer onCreate");
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE );	// 타이틀바 제거
		setContentView(R.layout.image_viewer_activity);

		commonUtil = new CommonUtil();

		upload_img_view = (ImageView) findViewById(R.id.image_view);	
		pb1 = (ProgressBar) findViewById(R.id.pb);	

		top_navi_close_btn = (Button) findViewById(R.id.top_navi_close_btn);
		// 상단 닫기 버튼
		top_navi_close_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d(TAG,"top_navi_close_btn clicked");
				finish();
			}
		});
		image_download_btn = (Button) findViewById(R.id.image_download_btn);
		image_download_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d(TAG,"image_download_btn clicked");
				//				finish();
				new backgroundThreadDownloadFromUrl().execute();
			}
		});


		Intent recievedIntent = getIntent();
		imageUrl = recievedIntent.getStringExtra("imageUrl");		
		Log.d(TAG,"imageUrl::"+imageUrl);
		new backgroundThreadshowUploadImage().execute();
	}






	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	// 자체 메소드

	public Context returnThis(){
		return this;
	}

	// 이미지 처리
	/**
	 * backgroundThreadshowUploadImage
	 * 비동기 . 이미지보기
	 * @author blue
	 *
	 */
	public class backgroundThreadshowUploadImage extends AsyncTask<Void, Void, Void>{
		@Override protected void onPostExecute(Void result) {  
		} 
		@Override protected void onPreExecute() {  
		} 
		@Override protected Void doInBackground(Void... params) {  
			showPb();
			temp_upload_img = LoadImage(imageUrl);
			showUploadImage(); 
			return null; 
		}
	}
	/**
	 * backgroundThreadDownloadFromUrl
	 * 비동기 . 이미지 다운
	 * @author blue
	 *
	 */
	public class backgroundThreadDownloadFromUrl extends AsyncTask<Void, Void, Void>{
		@Override protected void onPostExecute(Void result) {  
		} 
		@Override protected void onPreExecute() {  
		} 
		@Override protected Void doInBackground(Void... params) {  
			showPb();
			DownloadFromUrl(imageUrl, commonUtil.getNowDateForImage()+".png");
			hidePb();
			return null; 
		}
	}
	/**
	 * LoadImage
	 *  이미지 URL 에서 이미지 받아온 스트림을 비트맵으로 저장한다
	 *
	 * @param $imagePath
	 * @param
	 * @return bm
	 */
	private Bitmap LoadImage( String $imagePath ) {
		InputStream inputStream = OpenHttpConnection( $imagePath ) ;
		Bitmap bm = BitmapFactory.decodeStream( inputStream ) ;
		return bm;
	}
	/**
	 * OpenHttpConnection
	 *  이미지 URL 에서 이미지 받아와서 스트림으로 저장한다
	 *
	 * @param $imagePath
	 * @param
	 * @return stream
	 */
	private InputStream OpenHttpConnection(String $imagePath) {
		// TODO Auto-generated method stub
		InputStream stream = null ;
		try {
			URL url = new URL( $imagePath ) ;
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection() ;
			urlConnection.setRequestMethod( "GET" ) ;
			urlConnection.connect() ;
			if( urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK ) {
				stream = urlConnection.getInputStream() ;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return stream ;
	}
	/**
	 * showUploadImage
	 *  업로드 이미지 크게 보기
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void showUploadImage(){
		//  가져온 데이터로 화면타이틀을 변경한다.
		ImageViewer.this.runOnUiThread(new Runnable(){		 
			@Override
			public void run(){
				Message message = handler.obtainMessage();
				Bundle b = new Bundle();
				b.putInt("showUploadImage", 1);
				message.setData(b);
				handler.sendMessage(message);
			}
		});
	}


	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	

	// 파일 저장
	public void fileSave(){		// for test
		String path="/sdcard/TestMyImage";
		String fileName= "image.png";	
		String data = "";
		File file = new File(path+fileName);
		FileOutputStream fos = null;
		try{
			fos = new FileOutputStream(file);
			fos.write((data).getBytes());
			fos.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public void DownloadFromUrl(String DownloadUrl, String fileName) {
		try {
			File root = android.os.Environment.getExternalStorageDirectory();    
			Log.d(TAG,"root.getAbsolutePath():"+root.getAbsolutePath());
			String dirName = root.getAbsolutePath() + "/UsedMarketDownloadImg";
			File dir = new File (dirName);
			if(dir.exists()==false) {
				dir.mkdirs();
			}
			URL url = new URL(DownloadUrl); //you can write here any link
			File file = new File(dir, fileName);

			long startTime = System.currentTimeMillis();
			Log.d("DownloadManager", "download begining");
			Log.d("DownloadManager", "download url:" + url);
			Log.d("DownloadManager", "downloaded file name:" + fileName);

			/* Open a connection to that URL. */
			URLConnection ucon = url.openConnection();

			/*
			 * Define InputStreams to read from the URLConnection.
			 */
			InputStream is = ucon.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);

			/*
			 * Read bytes to the Buffer until there is nothing more to read(-1).
			 */
			ByteArrayBuffer baf = new ByteArrayBuffer(5000);
			int current = 0;
			while ((current = bis.read()) != -1) {
				baf.append((byte) current);
			}

			/* Convert the Bytes read to a String. */
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(baf.toByteArray());
			fos.flush();
			fos.close();
			Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");


//			showToast(getString(R.string.image_download_success));
			showToast(getString(R.string.image_download_success)+"\n("+dirName+"/"+fileName+")");

		} catch (IOException e) {
			Log.d("DownloadManager", "Error: " + e);
		}
	}


	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	/**
	 * showToast
	 *  화면에 error 토스트 띄운다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void showToast(final String msg){			// 화면에 error 토스트 띄움..
		new Thread(
				new Runnable(){
					public void run(){
						Message message = handler.obtainMessage();				
						Bundle b = new Bundle();
						b.putInt("showToast", 1);
						b.putString("msg", msg);
						message.setData(b);
						handler.sendMessage(message);
					}
				}
		).start();
	} 


	// 중앙 프로그래스바 보임, 숨김
	/**
	 * showPb
	 *  중앙 프로그래스바 가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void showPb(){
		new Thread( 
				new Runnable(){
					public void run(){
						Message message = handler .obtainMessage();
						Bundle b = new Bundle();
						b.putInt( "order" , 1);
						message.setData(b);
						handler .sendMessage(message);
					}
				}
		).start();
	}
	/**
	 * hidePb
	 *  중앙 프로그래스바 비가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void hidePb(){
		new Thread(
				new Runnable(){
					public void run(){
						Message message = handler .obtainMessage();
						Bundle b = new Bundle();
						b.putInt( "order" , 2);
						message.setData(b);
						handler .sendMessage(message);
					}
				}
		).start();
	}
}